package com.company.ddd.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.Driver;

/**
 * =================================
 * <p>
 * Created by cjj on 18-11-25.
 * <p>
 * 描述: 持久化配置
 */

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

    @Value("${project.datasource.driver}")
    private String driver;
    @Value("${project.datasource.url}")
    private String url;
    @Value("${project.datasource.username}")
    private String username;
    @Value("${project.datasource.password}")
    private String password;

    @Bean(value = "sessionFactory")
    public LocalSessionFactoryBean setSessionFactory() {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(setDataSource());
        localSessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
        return localSessionFactoryBean;
    }

    @Bean
    public DataSource setDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        try {
            druidDataSource.setDriver((Driver) Class.forName(driver).newInstance());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        druidDataSource.setUrl(this.url);
        druidDataSource.setUsername(this.username);
        druidDataSource.setPassword(this.password);
        return druidDataSource;
    }

    @Bean
    @ConditionalOnMissingBean(HibernateTransactionManager.class)
    public HibernateTransactionManager setTransactionManager() {
        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
        hibernateTransactionManager.setSessionFactory(setSessionFactory().getObject());
        return hibernateTransactionManager;
    }


}
